package com.zoncont.web.controller.estate;

import com.zoncont.common.annotation.Log;
import com.zoncont.common.config.datasource.DynamicDataSourceContextHolder;
import com.zoncont.common.core.controller.BaseController;
import com.zoncont.common.core.domain.AjaxResult;
import com.zoncont.common.core.domain.Ztree;
import com.zoncont.common.core.page.TableDataInfo;
import com.zoncont.common.enums.BusinessType;
import com.zoncont.common.enums.DataSourceType;
import com.zoncont.common.utils.EntityUtils;
import com.zoncont.common.utils.poi.ExcelUtil;
import com.zoncont.estate.formbean.ResetPwdFormBean;
import com.zoncont.framework.shiro.service.SysPasswordService;
import com.zoncont.framework.util.ShiroUtils;
import com.zoncont.estate.domain.Company;
import com.zoncont.estate.domain.Menu;
import com.zoncont.estate.domain.Role;
import com.zoncont.estate.domain.User;
import com.zoncont.estate.service.ICompanyService;
import com.zoncont.estate.service.IMenuService;
import com.zoncont.estate.service.ISaasMenuService;
import com.zoncont.estate.service.IUserService;
import com.zoncont.system.domain.SysUser;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 公司账号 信息操作处理
 *
 * @author zoncont.ahanu
 * @date 2019-04-08
 */
@Controller
@RequestMapping("/estate/company")
public class CompanyController extends BaseController {
    private String prefix = "estate/company";

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private IUserService userService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private IMenuService menuService;
    @Autowired
    private ISaasMenuService saasMenuService;

    /**
     * 修改保存用户
     */
    @Log(title = "用户管理" , businessType = BusinessType.INSERT)
    @PostMapping("/user/edit")
    @ResponseBody
    public AjaxResult editSave(Role role){
        List<Menu> menus =  menuService.selectMenuAll();
        role.setMenus(menus);
        DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE.name());
        User user = new User();
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword("admin", "123456", user.getSalt()));
        user.setCreateBy(ShiroUtils.getLoginName());
        user.setCompany(role.getCompany());
        user.setLoginName("admin");
        user.setUserName("系统管理员");
        userService.insertUser(role, user);
        DynamicDataSourceContextHolder.clearDataSourceType();
        DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.MASTER.name());
        return AjaxResult.success();
    }

    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @GetMapping("/resetPwd/{compId}")
    public String resetPwd(@PathVariable("compId") String compId, ModelMap mmap) {
        DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE.name());
        mmap.put("userId", userService.selectUserIdByCompId(compId));
        DynamicDataSourceContextHolder.clearDataSourceType();
        DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.MASTER.name());
        return prefix + "/resetPwd";
    }

    @RequiresPermissions("estate:company:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    @ApiOperation(value = "重置密码")
    public AjaxResult resetPwdSave(ResetPwdFormBean form) {
        User user = new User();
        user.setUserId(form.getUserId());
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword("admin", form.getPassword(), user.getSalt()));
        DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE.name());
        int result = userService.resetUserPwd(user);
        DynamicDataSourceContextHolder.clearDataSourceType();
        DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.MASTER.name());
        return toAjax(result);
    }

    /**
     * 加载公司菜单列表树
     */
    @GetMapping("/roleMenuTreeData/{companyId}")
    @ResponseBody
    public List<Ztree> roleMenuTreeData(@PathVariable("companyId") String companyId) {
        List<Menu> menuList = menuService.selectMenuAll();
        DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE.name());
        // 当前公司拥有的权限
        List<String> companyMenuList = saasMenuService.selectMenuTree(companyId);
        DynamicDataSourceContextHolder.clearDataSourceType();
        DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.MASTER.name());
        List<Ztree> ztrees = saasMenuService.menuTreeDataByCompany(menuList, companyMenuList);
        return ztrees;
    }

    @RequiresPermissions("estate:company:view")
    @GetMapping()
    public String company() {
        return prefix + "/company";
    }

    /**
     * 查询公司账号列表
     */
    @RequiresPermissions("estate:company:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Company company) {
        startPage();
        List<Company> list = companyService.selectCompanyList(company);
        return getDataTable(list);
    }

    /**
     * 导出公司账号列表
     */
    @RequiresPermissions("estate:company:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Company company) {
        List<Company> list = companyService.selectCompanyList(company);
        ExcelUtil<Company> util = new ExcelUtil<Company>(Company.class);
        return util.exportExcel(list, "company");
    }

    /**
     * 新增公司账号
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增公司账号
     */
    @GetMapping("/user/edit/{id}")
    public String add(@PathVariable("id") String compId, ModelMap mmap) {
        mmap.put("company" , compId);
        return prefix + "/editRole";
    }

    /**
     * 新增保存公司账号
     */
    @RequiresPermissions("estate:company:add")
    @Log(title = "公司账号", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Company company) {
        EntityUtils.setCreateInfo(company);
        company.setStatus("1");
        return toAjax(companyService.insertCompany(company));
    }

    /**
     * 修改公司账号
     */
    @GetMapping("/edit/{companyId}")
    public String edit(@PathVariable("companyId") Integer companyId, ModelMap mmap) {
        Company company = companyService.selectCompanyById(companyId);
        mmap.put("company", company);
        return prefix + "/edit";
    }

    /**
     * 修改保存公司账号
     */
    @RequiresPermissions("estate:company:edit")
    @Log(title = "公司账号", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Company company) {
        EntityUtils.setUpdatedInfo(company);
        return toAjax(companyService.updateCompany(company));
    }

    /**
     * 删除公司账号
     */
    @RequiresPermissions("estate:company:remove")
    @Log(title = "公司账号", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(companyService.deleteCompanyByIds(ids));
    }

    /**
     * 校验公司名称
     */
    @GetMapping("/checkNameUnique")
    @ResponseBody
    public String checkNameUnique(Company company) {
        return companyService.checkNameUnique(company);
    }

    /**
     * 校验公司登录码
     */
    @GetMapping("/checkAccountUnique")
    @ResponseBody
    public String checkAccountUnique(Company company) {
        return companyService.checkAccountUnique(company);
    }

    /**
     * 校验公司标识码
     */
    @GetMapping("/checkCompIdUnique")
    @ResponseBody
    public String checkCompIdUnique(Company company) {
        return companyService.checkCompIdUnique(company);
    }


}
